<template>
    <div class="container">
        <!-- 面包屑 -->
        <div class="bread-container">
            <el-breadcrumb separator=">">
                <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
                <el-breadcrumb-item :to="{ path: `/category/${filterData.parentId}` }">{{ filterData.parentName }}</el-breadcrumb-item>
                <el-breadcrumb-item>{{ filterData.name }}</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="sub-container">
            <el-tabs v-model="reqData.sortField" @tab-change="tagChange">
                <el-tab-pane label="最新商品" name="publishTime"></el-tab-pane>
                <el-tab-pane label="最高人气" name="orderNum"></el-tab-pane>
                <el-tab-pane label="评论最多" name="evaluateNum"></el-tab-pane>
            </el-tabs>
            <div class="body" v-infinite-scroll="load" :infinite-scroll-disabled="disabled">
                <!-- 商品列表 -->
                <GoodsItem v-for="good in goodList" :key="good.id" :good="good"/>
            </div>
        </div>
    </div>
</template>

<script setup>
    import { useRoute } from 'vue-router'
    import { reactive,onMounted,ref } from 'vue'
    import { getCategoryFilterAPI,getSubCategoryAPI } from '@/apis/category'
    import GoodsItem from '@/views/Home/components/GoodsItem.vue'

    const route = useRoute()
    const filterData = reactive({})

    const getFilterData = async (id) => {
        const { result } = await getCategoryFilterAPI(id)
        Object.assign(filterData,result)
    } 

    onMounted(() => {
        getFilterData(route.params.id)
        console.log(filterData)
    })

    //获取二级分类商品
    let goodList = reactive([])
    const reqData = reactive({
        category:route.params.id,
        page:1,
        pageSize:20,
        sortField:'publishTime'
    })

    const getGoodList = async () => {
        const { result:{items} } = await getSubCategoryAPI(reqData)
        Object.assign(goodList,items)
    }

    onMounted(() => {
        getGoodList()
    })

    const tagChange = () => {
        console.log('tab切换了',reqData.sortField)
        reqData.page = 1
        getGoodList()
    }

    //禁用无线加载
    const disabled = ref(false)

    //无限加载
    const load = async () => {
        reqData.page ++
        const { result:{items} } = await getSubCategoryAPI(reqData)
        // goodList = goodList.concat(items)
        // goodList = [...goodList,...items] 
        if(items.length === 0){
            disabled.value = true
        }
        
        // reactive响应式数组要用这种拼接方式，才能保持响应式
        goodList.push(...items)

    }
</script>

<style lang="scss" scoped>
    .bread-container {
        padding: 25px 0;
        color: #666;
    }

    .sub-container {
        padding: 20px 10px;
        background-color: #fff;

        .body {
            display: flex;
            flex-wrap: wrap;
            padding: 0 10px;
        }
    }

</style>